package com.yeswater.multithread.chapter7;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * author : yeswater
 * date : 2023/11/6
 * <p>
 * SimpleDateFormat 非线程安全
 *  1. 创建多个 SimpleDateFormat 实例解决
 */

public class Run_7_6_2 {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String[] dateStrArr = new String[]{"2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04", "2000-01-05", "2000-01-06", "2000-01-07", "2000-01-08", "2000-01-09", "2000-01-10"};

        Thread1[] threadArr = new Thread1[10];
        for (int i = 0; i < 10; i++) {
            threadArr[i] = new Thread1(sdf, dateStrArr[i]);
        }

        for (int i = 0; i < 10; i++) {
            threadArr[i].start();
        }
    }

    private static class Thread1 extends Thread {
        private SimpleDateFormat sdf;
        private String date;

        public Thread1(SimpleDateFormat sdf, String date) {
            super();
            this.sdf = sdf;
            this.date = date;
        }

        @Override
        public void run() {
            try {
                Date dateRef = DateTools.parse("yyyy-MM-dd", date);
                String newDate = DateTools.format("yyyy-MM-dd", dateRef);
                if (!newDate.equals(date)) {
                    System.out.println("ThreadName=" + this.getName() + " 报错了 日期字符串:" + date + " 转换成的日期为: " + newDate);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private static class DateTools {
        public static Date parse(String formatPattern, String dateStr) throws ParseException {
            return new SimpleDateFormat(formatPattern).parse(dateStr);
        }

        public static String format(String formatPattern, Date date)  {
            return new SimpleDateFormat(formatPattern).format(date);
        }
    }
}
